'''
@Author: hua
@Date: 2018-08-30 10:52:23
@LastEditors  : hua
@LastEditTime : 2019-12-18 14:52:28
'''
import sys
from datetime import timedelta

from flask import Flask
# 权限模块 https://github.com/raddevon/flask-permissions
# from flask_permissions.core import Permissions
from apscheduler.schedulers.blocking import BlockingScheduler
from flask_cors import CORS
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from flask_socketio import SocketIO

from app.Vendor.Code import Code
import environment as e
from app.Vendor.Log import log
from app.env import SQLALCHEMY_DATABASE_URI, SQLALCHEMY_TRACK_MODIFICATIONS, PASSERBY_UPLOAD_FOLDER, MAX_CONTENT_LENGTH, \
    DEBUG_LOG, SAVE_LOG
import os, json

# 读取启动环境
environment = e.read()

# 普通json带error_code风格使用此app示例
app = Flask(__name__, static_folder='Uploads', static_url_path='/api/user/uploads')

# 注册权限
# perms = Permissions(app, db, None)
# 实例化websocket
async_mode = 'gevent'
socketio = SocketIO(app, async_mode=async_mode)
# 配置 sqlalchemy  数据库驱动://数据库用户名:密码@主机地址:端口/数据库?编码
app.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = SQLALCHEMY_TRACK_MODIFICATIONS
# 上传文件配置
app.config['UPLOAD_FOLDER'] = PASSERBY_UPLOAD_FOLDER  # 上传目录
app.config['MAX_CONTENT_LENGTH'] = MAX_CONTENT_LENGTH  # 上传大小
# 设置session过期时间
app.config['SECRET_KEY'] = os.urandom(24)
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=3)  # 设置cookie 的时间为3天
# 创建数据库及连接
engine = create_engine(SQLALCHEMY_DATABASE_URI)
# 创建DBSession类型:
DBSession = sessionmaker(bind=engine)
dBSession = DBSession()
# 引入数据库事件
from app.Event import Log
from app.Vendor.ApiException import ApiException, ParameterErr


@app.teardown_appcontext
def shutdown_session(exception=None):
    dBSession.close()


# 挂载500异常处理,并记录日志
# if environment == 'run' or environment == 'restful':
@app.errorhandler(ApiException)
def error_handler(e):
    # 记录错误日志
    if DEBUG_LOG:
        if SAVE_LOG == 1:
            log().exception(e)
    return e.to_result()


@app.errorhandler(Exception)
def handler_err(e):
    if DEBUG_LOG:
        if SAVE_LOG == 1:
            log().exception(e)
    err = ApiException()
    return err.to_result()


@app.errorhandler(404)
def handle_404(err):
    err = ParameterErr('api接口不存在')
    return err.to_result()


if environment == 'socket':
    @socketio.on_error_default  # Handles the default namespace
    def error_handler(e):
        return ApiException(Code.ERROR, e)
# 引入使用的控制器
if environment == 'run' or environment == 'restful':
    from app.Controllers import UsersController, RestfulController, AdminController, PCAController
    # 蓝图，新增的后台部分代码
    from app.Controllers.AdminController import admin

    app.register_blueprint(admin, url_prefix='/admin')
    from app.Controllers.PCAController import pca

    app.register_blueprint(pca, url_prefix='/api/pca')
    from app.Controllers.PLSDAController import plsda

    app.register_blueprint(plsda, url_prefix='/api/plsda')
    from app.Controllers.UnivariateAnalysisController import ua

    app.register_blueprint(ua, url_prefix='/api/ua')
    from app.Controllers.PowerAnalysisController import pa

    app.register_blueprint(pa, url_prefix='/api/pa')
    from app.Controllers.SteinerTreeController import st

    app.register_blueprint(st, url_prefix='/api/st')
if environment == 'socket':
    # 引入socketio控制层
    from app.Controllers import SocketController

# 使用nginx进行跨域
CORS(app, supports_credentials=True)
